﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms;
using System.Windows.Controls;

using System.Drawing;
using Brushes = System.Windows.Media.Brushes;
using Brush = System.Windows.Media.Brush;
using ComboBox = System.Windows.Controls.ComboBox;
using FontFamily = System.Windows.Media.FontFamily;
using Image = System.Windows.Controls.Image;
using MouseEventArgs = System.Windows.Input.MouseEventArgs;
using Point = System.Windows.Point;
using Rectangle = System.Windows.Shapes.Rectangle;

namespace C_sports_meet.Manager
{
    /// <summary>
    /// InkPage.xaml 的交互逻辑
    /// </summary>
    public partial class InkPage : Page
    {
        private bool _isDrawing = false;
        private Point _startPoint;
        private Brush _brush;
        private double _brushSize = 10;
        private ShapeType _shapeType = ShapeType.Circle;
        private Brush _fillBrush = Brushes.Transparent;
        private double _opacity = 1;
        private Style _style = null;
        private bool _eraserEnabled = false;
        private Point _lastPoint;
        private Line lineline = null;

        public InkPage()
        {
            InitializeComponent();
            _brush = Brushes.Black;
            Canvas canvas = (Canvas)FindName("canvas");
        }

        private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (_eraserEnabled)
            {
                Canvas canvas = sender as Canvas;
                HitTestResult hitResult = VisualTreeHelper.HitTest(canvas, e.GetPosition(canvas));
                if (hitResult != null && hitResult.VisualHit is Shape)
                {
                    Shape shape = hitResult.VisualHit as Shape;
                    canvas.Children.Remove(shape);
                }
            }
            else
            {
                _isDrawing = true;
                _startPoint = e.GetPosition(canvas);
                _lastPoint = _startPoint;

                Shape shape = CreateShape();
                canvas.Children.Add(shape);

                Canvas.SetLeft(shape, _startPoint.X);
                Canvas.SetTop(shape, _startPoint.Y);
            }

        }

        private void Canvas_MouseMove(object sender, MouseEventArgs e)
        {
            if (_isDrawing)
            {
                Canvas canvas = sender as Canvas;
                Point currentPoint = e.GetPosition(canvas);
                if (canvas.Children.Count > 0)
                {
                    Shape shape = canvas.Children[canvas.Children.Count - 1] as Shape;
                    if (_shapeType == ShapeType.Line)
                    {
                        Line line = shape as Line;
                        line.X2 = currentPoint.X - _startPoint.X;
                        line.Y2 = currentPoint.Y - _startPoint.Y;
                    }
                    else
                    {
                        double width = currentPoint.X - _startPoint.X;
                        double height = currentPoint.Y - _startPoint.Y;
                        double left = _startPoint.X;
                        double top = _startPoint.Y;

                        if (width < 0)
                        {
                            left = currentPoint.X;
                            width = Math.Abs(width);
                        }
                        if (height < 0)
                        {
                            top = currentPoint.Y;
                            height = Math.Abs(height);
                        }

                        if (_shapeType == ShapeType.Rectangle)
                        {
                            Rectangle rect = shape as Rectangle;
                            rect.Width = width;
                            rect.Height = height;
                            Canvas.SetLeft(rect, left);
                            Canvas.SetTop(rect, top);
                        }
                        else if (_shapeType == ShapeType.Circle)
                        {
                            Ellipse ellipse = shape as Ellipse;
                            ellipse.Width = width;
                            ellipse.Height = height;
                            Canvas.SetLeft(ellipse, left);
                            Canvas.SetTop(ellipse, top);
                        }
                    }

                    _lastPoint = currentPoint;
                }
            }
        }

        private void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (_isDrawing)
            {
                _isDrawing = false;
                Shape shape = canvas.Children[canvas.Children.Count - 1] as Shape;
                if (_style != null)
                {
                    shape.Style = _style;
                }
            }
        }

        private void SizeComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox comboBox = sender as ComboBox;
            ComboBoxItem selectedItem = comboBox.SelectedItem as ComboBoxItem;
            switch (selectedItem.Content.ToString())
            {
                case "Small":
                    _brushSize = 5;
                    break;
                case "Medium":
                    _brushSize = 10;
                    break;
                case "Large":
                    _brushSize = 20;
                    break;
            }
        }

        private void ShapeComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox comboBox = sender as ComboBox;
            ComboBoxItem selectedItem = comboBox.SelectedItem as ComboBoxItem;
            switch (selectedItem.Content.ToString())
            {
                case "Circle":
                    _shapeType = ShapeType.Circle;
                    break;
                case "Rectangle":
                    _shapeType = ShapeType.Rectangle;
                    break;
                case "Line":
                    _shapeType = ShapeType.Line;
                    break;
            }
        }

        private void StyleComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox comboBox = sender as ComboBox;
            ComboBoxItem selectedItem = comboBox.SelectedItem as ComboBoxItem;
            switch (selectedItem.Content.ToString())
            {
                case "Solid":
                    _style = null;
                    break;
                case "Dashed":
                    _style = (Style)this.FindResource("DashedStyle");
                    break;
                case "Dotted":
                    _style = (Style)this.FindResource("DottedStyle");
                    break;
            }
        }

        private void ColorButton_Click(object sender, RoutedEventArgs e)
        {
            ColorDialog colorDialog = new ColorDialog();
            if (colorDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                _brush = new SolidColorBrush(System.Windows.Media.Color.FromRgb(colorDialog.Color.R, colorDialog.Color.G, colorDialog.Color.B));
                ColorButton.Background = _brush;
            }
        }

        private void ClearButton_Click(object sender, RoutedEventArgs e)
        {
            canvas.Children.Clear();
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = "Document"; // Default file name
            dlg.DefaultExt = ".png"; // Default file extension
            dlg.Filter = "PNG files (.png)|*.png"; // Filter files by extension

            // Show save file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            // Process save file dialog box results
            if (result == true)
            {
                // Save document
                string filename = dlg.FileName;
                SaveCanvasToFile(canvas, filename);
            }
        }

        private void LoadButton_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.FileName = "Document"; // Default file name
            dlg.DefaultExt = ".png"; // Default file extension
            dlg.Filter = "PNG files (.png)|*.png"; // Filter files by extension

            // Show open file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            // Process open file dialog box results
            if (result == true)
            {
                // Load document
                string filename = dlg.FileName;
                LoadCanvasFromFile(canvas, filename);
            }
        }

        private void EraserButton_Checked(object sender, RoutedEventArgs e)
        {
            _eraserEnabled = true;
        }

        private void EraserButton_Unchecked(object sender, RoutedEventArgs e)
        {
            _eraserEnabled = false;
        }

        private void InsertImageButton_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.FileName = "Image"; // Default file name
            dlg.DefaultExt = ".png"; // Default file extension
            dlg.Filter = "PNG files (.png)|*.png"; // Filter files by extension

            // Show open file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            // Process open file dialog box results
            if (result == true)
            {
                // Load image
                string filename = dlg.FileName;
                Image image = new Image();
                image.Source = new BitmapImage(new Uri(filename, UriKind.Absolute));

                // Add to canvas
                canvas.Children.Add(image);
                Canvas.SetLeft(image, _startPoint.X);
                Canvas.SetTop(image, _startPoint.Y);
            }
        }

        private void InsertTextButton_Click(object sender, RoutedEventArgs e)
        {
            TextBlock textBlock = new TextBlock();
            textBlock.Text = "Text";
            textBlock.Foreground = _brush;
            textBlock.FontSize = _brushSize;
            textBlock.FontFamily = new FontFamily("Arial");
            canvas.Children.Add(textBlock);
            Canvas.SetLeft(textBlock, _startPoint.X);
            Canvas.SetTop(textBlock, _startPoint.Y);
        }

        private Shape CreateShape()
        {
            Shape shape = null;
            switch (_shapeType)
            {
                case ShapeType.Circle:
                    Ellipse ellipse = new Ellipse();
                    ellipse.Stroke = _brush;
                    ellipse.Fill = _fillBrush;
                    ellipse.StrokeThickness = _brushSize;
                    ellipse.Width = 0;
                    ellipse.Height = 0;
                    shape = ellipse;
                    break;
                case ShapeType.Rectangle:
                    Rectangle rect = new Rectangle();
                    rect.Stroke = _brush;
                    rect.Fill = _fillBrush;
                    rect.StrokeThickness = _brushSize;
                    rect.Width = 0;
                    rect.Height = 0;
                    shape = rect;
                    break;
                case ShapeType.Line:
                    Line line = new Line();
                    line.Stroke = _brush;
                    line.StrokeThickness = _brushSize;
                    line.X1 = 0;
                    line.Y1 = 0;
                    line.X2 = 0;
                    line.Y2 = 0;
                    shape = line;
                    lineline = line; // 将 line 赋值给 lineline 变量
                    break;
            }
            if (_style != null)
            {
                shape.Style = _style;
            }

            shape.Opacity = _opacity;

            return shape;
        }

        private void SaveCanvasToFile(Canvas canvas, string filename)
        {
            Rect bounds = VisualTreeHelper.GetDescendantBounds(canvas);

            double dpi = 96d;
            RenderTargetBitmap rtb = new RenderTargetBitmap((int)bounds.Width, (int)bounds.Height, dpi, dpi, PixelFormats.Pbgra32);
            DrawingVisual dv = new DrawingVisual();
            using (DrawingContext dc = dv.RenderOpen())
            {
                VisualBrush vb = new VisualBrush(canvas);
                dc.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
            }
            rtb.Render(dv);

            PngBitmapEncoder png = new PngBitmapEncoder();
            png.Frames.Add(BitmapFrame.Create(rtb));

            using (Stream stm = File.Create(filename))
            {
                png.Save(stm);
            }
        }

        private void LoadCanvasFromFile(Canvas canvas, string filename)
        {
            Image image = new Image();
            image.Source = new BitmapImage(new Uri(filename, UriKind.Absolute));
            canvas.Children.Add(image);
        }

        private enum ShapeType
        {
            Circle,
            Rectangle,
            Line
        }
    }
}

